package cn.redcoral.chattest;

import java.util.*;

/**
 * @author mo
 * @日期: 2024-09-20 19:22
 **/
public class Main {
    public static int[][] findIntersection (int[][] firstList, int[][] secondList) {
        List<int[]> res = new ArrayList<>();
        Map<Double, Integer> map = new TreeMap<>();
        for (int i = 0; i < firstList.length; i++) {
            int j = 0;
            for(j = firstList[i][0]; j <= firstList[i][1]; j++) {
                Integer x = map.get((double) j);
                if (x==null) {
                    map.put((double) j, 1);
                } else {
                    map.put((double) j, x+1);
                }
            }
            map.put(j-0.5, -1);
        }
        for (int i = 0; i < secondList.length; i++) {
            int j = 0;
            for(j = secondList[i][0]; j <= secondList[i][1]; j++) {
                Integer x = map.get((double) j);
                if (x==null) {
                    map.put((double) j, 1);
                } else {
                    map.put((double) j, x+1);
                }
            }
            map.put(j+0.5, -1);
        }
        int start = -1;
        int end = -1;
        for (Map.Entry<Double, Integer> integerIntegerEntry : map.entrySet()) {
            Integer k = integerIntegerEntry.getKey().intValue();
            Integer v = integerIntegerEntry.getValue();
            if (v==-1) {
                if (start!=-1) {
                    if (end!=-1) {
                        res.add(new int[]{start, end});
                        end = -1;
                    } else {
                        res.add(new int[]{start, start});
                    }
                    start = -1;
                }
            } else if (v>=2) {
                if (start==-1) {
                    start = k;
                } else {
                    end = k;
                }
            } else {
                if (start!=-1) {
                    if (end!=-1) {
                        res.add(new int[]{start, end});
                        end = -1;
                    } else {
                        res.add(new int[]{start, start});
                    }
                    start = -1;
                }
            }
        }
        return res.toArray(new int[res.size()][]);
    }

    public static void main(String[] args) {
        int[][] firstList = {{1,2},{3,4}};
        int[][] secondList = {{2,3}};
        int[][] intersection = findIntersection(firstList, secondList);
        for (int i = 0; i < intersection.length; i++) {
            for (int j = 0; j < intersection[i].length; j++) {
                System.out.print(intersection[i][j] + " ");
            }
            System.out.println();
        }
    }
}
